﻿Imports System
Imports System.IO
Imports System.Data.OleDb
Imports System.Data

Imports System.Net.Mail
Imports System.Web.Mail
Imports iTextSharp.text

Imports iTextSharp.text.pdf


Namespace Arwani
    Partial Class index
        Inherits System.Web.UI.Page
        Public sent As Boolean = False
        Public already As Boolean = False
        Protected BannerHTML As String = ""
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Call ShowDiv()
            Call loadHomePageBanners()
            Call loadHeader()

            If Request.QueryString("sent") = 1 Then
                sent = True
            End If
            If Request.QueryString("already") = 1 Then
                already = True
            End If
            Call setPageSEOInformation()
        End Sub

        Public Sub ShowDiv()

            Dim arwcon2 As New ArwaniController
            'First of all check the Raffel Master have default Value or not
            Dim strCheckValueExists As String = "Select Count(*) from RaffleMaster where Active=1"
            Dim dtExists As DataTable = arwcon2.ExecuteQuery(strCheckValueExists)

            If dtExists.Rows(0)(0).ToString = "0" Then

                tblRfl.Visible = False
                tblExpired.Visible = True

            Else

                'check if Raffel Exists then Is it is Expired.
                Dim strCheckValueDate As String = "Select EndDate from RaffleMaster where Active=1"
                Dim dtExistsR As DataTable = arwcon2.ExecuteQuery(strCheckValueDate)
                Dim strCheckValuecom As Date = Convert.ToDateTime(dtExistsR.Rows(0)(0).ToString)
                Dim todaysdate As Date = DateTime.Now.Date
                If todaysdate > strCheckValuecom Then
                    tblRfl.Visible = False
                    tblExpired.Visible = True
                Else
                    tblRfl.Visible = True
                    tblExpired.Visible = False

                End If
            End If

        End Sub

        Public Sub loadHeader()
            Dim arwCon As New ArwaniController
            Dim strQ As String = "select * from RaffleMaster where id=1"
            Dim dtTable As DataTable = arwCon.ExecuteQuery(strQ)

            Dim iCount As Integer = 0
            If dtTable.Rows.Count > 0 Then
                If Not IsDBNull(dtTable.Rows(0)("Description")) Then lblHeader.Text = dtTable.Rows(0)("Description")
                
            End If
        End Sub


        Public Sub loadHomePageBanners()
            Dim arwCon As New ArwaniController
            Dim strQ As String = "select * from home_page_banners order by sortorder "
            Dim dtTable As DataTable = arwCon.ExecuteQuery(strQ)
            Dim iCount As Integer = 0

            Dim arrDataStartalign() As String = {"right,bottom", "top,right", "left,bottom", "right,top", "center,top", "right,bottom", "center,bottom"}

            Dim arrDataZoom() As String = {"in", "out"}


            Dim arrDataTransition() As String = {"fade", "slide"}


            Dim arrDataZoomFact() As String = {"1", "1.2", "1.1", "1.3", "1.5", "1.9", "1.0"}


            Dim arrDataPanduration() As String = {"12", "14", "18", "9", "10", "17", "13"}


            Dim arrDataEndAlign() As String = {"center,top", "left,bottom", "center,center", "center,bottom", "right,top", "right,bottom", "center,right"}

            Dim DataStartalign As Integer = 0
            Dim DataZoom As Integer = 0
            Dim DataZoomFact As Integer = 0
            Dim DataTransition As Integer = 0
            Dim DataEndAlign As Integer = 0
            Dim DataPanduration As Integer = 0


            For iCount = 0 To dtTable.Rows.Count - 1

                BannerHTML &= "<li data-transition='" & arrDataTransition(DataTransition) & "' data-startalign='" & arrDataStartalign(DataStartalign) & "' data-zoom='" & arrDataZoom(DataZoom) & "' data-zoomfact='" & arrDataZoomFact(DataZoomFact) & "' data-endalign='" & arrDataEndAlign(DataEndAlign) & "' data-panduration='" & arrDataPanduration(DataPanduration) & "' data-colortransition='4'><img alt='' src='" & getImage("HomeBanners", "", dtTable.Rows(iCount)("banner_image")) & "' />"
                BannerHTML &= "<div class='creative_layer'>"
                BannerHTML &= "<div class='cp-left faderight'>"
                BannerHTML &= " <p class='cp-title'>&nbsp; </p>"
                BannerHTML &= "<div class='clear'> </div>"
                BannerHTML &= "</div>"
                BannerHTML &= "</div>"
                BannerHTML &= "</li>"
                'End If

                DataStartalign = DataStartalign + 1
                If DataStartalign = 7 Then
                    DataStartalign = 0
                End If
                DataZoom = DataZoom + 1
                If DataZoom = 2 Then
                    DataZoom = 0
                End If
                DataZoomFact = DataZoomFact + 1
                If DataZoomFact = 7 Then
                    DataZoomFact = 0
                End If

                DataTransition = DataTransition + 1
                If DataTransition = 2 Then
                    DataTransition = 0
                End If
                DataEndAlign = DataEndAlign + 1
                If DataEndAlign = 7 Then
                    DataEndAlign = 0
                End If

                DataPanduration = DataPanduration + 1
                If DataPanduration = 7 Then
                    DataPanduration = 0
                End If

            Next
        End Sub

        Public Function getImage(ByVal _Folder As String, ByVal Prefix As String, ByVal imgSrc As String) As String
            Dim strReturn As String = "../images/main_banner.png"
            If File.Exists(Server.MapPath("../" & _Folder & "/" & Prefix & imgSrc)) Then
                strReturn = "../" & _Folder & "/" & Prefix & imgSrc
            End If
            Return strReturn
        End Function
        Public Sub setPageSEOInformation()
            Dim thisURL As String = Request.Url.AbsoluteUri.Substring(Request.Url.AbsoluteUri.LastIndexOf("/") + 1)
            thisURL = thisURL.Substring(0, thisURL.IndexOf(".aspx") + 5)
            Dim keyword As New HtmlMeta
            keyword.Name = "keyword"
            Dim description As New HtmlMeta
            description.Name = "Description"
            Dim arwCon As New ArwaniController
            Dim strQ As String = "select * from AddSEO where PageName='" & thisURL.ToLower() & "'"
            Dim dtTable As DataTable = arwCon.ExecuteQuery(strQ)
            Dim iCount As Integer = 0
            If dtTable.Rows.Count > 0 Then
                If Not IsDBNull(dtTable.Rows(0)("Title")) Then Page.Title = dtTable.Rows(0)("Title")
                If Not IsDBNull(dtTable.Rows(0)("keywords")) Then keyword.Content = dtTable.Rows(0)("keywords")
                If Not IsDBNull(dtTable.Rows(0)("Description")) Then description.Content = dtTable.Rows(0)("Description")
            End If
            Page.Header.Controls.Add(keyword)
            Page.Header.Controls.Add(description)
        End Sub

        Protected Sub btnSendRaffle_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendRaffle.Click
            Dim arwcon2 As New ArwaniController
            'First of all check the Raffel Master have default Value or not
            Dim strCheckValueExists As String = "Select Count(*) from RaffleMaster where Active=1"
            Dim dtExists As DataTable = arwcon2.ExecuteQuery(strCheckValueExists)




            If dtExists.Rows(0)(0).ToString = "0" Then

                Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "adminalert();", True)

            Else

                'check if Raffel Exists then Is it is Expired.
                Dim strCheckValueDate As String = "Select EndDate from RaffleMaster where Active=1"
                Dim dtExistsR As DataTable = arwcon2.ExecuteQuery(strCheckValueDate)
                Dim strCheckValuecom As Date = Convert.ToDateTime(dtExistsR.Rows(0)(0).ToString)
                Dim todaysdate As Date = DateTime.Now.Date
                If todaysdate > strCheckValuecom Then

                    Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "Expirealert();", True)

                Else

                    Dim strRNameMain As String = "Select Name from RaffleMaster where Active=1"
                    Dim dtRNameMain As DataTable = arwcon2.ExecuteQuery(strRNameMain)

                    'createpdf()

                    Dim code As String = codeGenerated(4)
                    code = "AR-" & code
                    Dim strCheck As String = "Select Count(*) from Raffle where EmailID='" & txtEmailRaffle.Text & "' AND CurrentDate='" & DateTime.Now.ToString("d") & " 12:00:00 AM'"
                    Dim dt As DataTable = arwcon2.ExecuteQuery(strCheck)
                    Dim strmsg As String = String.Empty
                    Dim encode As Byte() = New Byte(code.Length - 1) {}
                    encode = Encoding.UTF8.GetBytes(code)
                    strmsg = Convert.ToBase64String(encode)

                    If dt.Rows(0)(0).ToString = "0" Then

                        'get RaffelName and CurrentDate

                        Dim strRName As String = "Select Name from RaffleMaster where Active=1"
                        Dim dtRName As DataTable = arwcon2.ExecuteQuery(strRName)

                        Dim getName As String = dtRName.Rows(0)(0).ToString
                        Dim currentdate As String = DateTime.Now.ToString("d")


                        Dim strQuery As String = "Insert into Raffle (ContactName,ComapanyName,OfficePhoneNumber,MobilePhoneNumber,EmailID,Code,RaffleName,CurrentDate) values ('" & txtContactNameRaffle.Text & "','" & txtCompanyNameRaffle.Text & "','" & txtOfficeNumberRaffle.Text & "','" & txtMobileNumberRaffle.Text & "','" & txtEmailRaffle.Text & "','" & code & "','" & getName & "', '" & currentdate & "')"
                        arwcon2.ExecuteNonQuery(strQuery)
                        Dim strMessage As String = ""
                        strMessage = "Hi " & Me.txtContactNameRaffle.Text & "<br><br>"
                        strMessage &= "Thank you for your registration, we look forward to welcoming you on our booth at Automechanika Dubai. Good luck to be the raffle winner <br/><br/>"
                        strMessage &= " <a href='http://www.arwani.ae.asp1-19.ord1-1.websitetestlink.com/CouponCode.aspx?ID=" & strmsg & "' target='_blank'>Click Here </a> For coupon code. <br/>"
                        'strMessage &= " <a href='http://localhost:54336/arwani.ae/CouponCode.aspx?ID=" & strmsg & "' target='_blank'>Click Here </a> For coupon code.<br/>"
                        strMessage &= "Please print out the code  and bring it to the exhibition <br/><br/> Thanks"
                        Dim title As [String] = "Raffle Enquiry - Arwani Trading Website "
                        Dim toAccount As [String] = txtEmailRaffle.Text
                        'String toAccount = "niteshguleria@nascenture.com";
                        Dim MyHost As [String] = "smtp.gmail.com"
                        Dim MySMTPPort As [String] = "587"
                        Dim MySMTPSSL As [String] = "true"
                        Dim fromAddr As [String] = "ae.arwani@gmail.com"
                        'Dim fromAddr As [String] = "sahilk@nascenture.com"
                        'Email Address of Sender
                        Dim smtpMssg As New System.Net.Mail.MailMessage()
                        smtpMssg.From = New MailAddress(fromAddr)
                        If toAccount.Contains(",") Then
                            Dim tos As String() = toAccount.Split(","c)
                            For i As Integer = 0 To tos.Length - 1
                                If tos(i) = "," OrElse tos(i) = "" Then
                                Else
                                    smtpMssg.[To].Add(New MailAddress(tos(i).Replace(",", "")))
                                End If
                            Next
                        Else
                            smtpMssg.[To].Add(New MailAddress(toAccount))
                        End If
                        'Dim str As String = Server.MapPath("Sample.pdf")
                        'Dim stream As FileStream = File.OpenRead(str)
                        'Dim attachment As Attachment = New Attachment(stream, "Code.pdf")
                        smtpMssg.Subject = title
                        smtpMssg.Body = strMessage
                        'smtpMssg.Attachments.Add(attachment)
                        smtpMssg.IsBodyHtml = True
                        Dim smtpClient As New System.Net.Mail.SmtpClient(MyHost, Convert.ToInt32(MySMTPPort))
                        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network
                        If MySMTPSSL = "true" Then
                            smtpClient.EnableSsl = True
                        End If
                        Try
                            smtpClient.Send(smtpMssg)
                            lblSuccessmsg.Text = ""
                            'lblSuccessmsg.Text = "Thank You for Registering, Please check your email for the Raffel Code The draw is 13th june at Arwani both in Hall 8 at 3 pm"
                            Response.Redirect("~/Raffle/index.aspx?sent=1", True)
                            'sent = True
                        Catch ex As Exception
                            Throw New Exception("Email not sent | Reason: [" + ex.Message & "]")
                        End Try
                    Else
                        lblSuccessmsg.Text = "Sorry, but you are already signed up for this raffle."
                        Response.Redirect("~/Raffle/index.aspx?already=1")

                    End If


                End If
            End If

        End Sub
        Protected Function codeGenerated(ByVal PasswordLength As Integer) As String
            Dim _allowedChars As String = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
            Dim randNum As New Random()
            Dim chars As Char() = New Char(PasswordLength - 1) {}
            Dim allowedCharCount As Integer = _allowedChars.Length
            For i As Integer = 0 To PasswordLength - 1
                chars(i) = _allowedChars(CInt((_allowedChars.Length) * randNum.NextDouble()))
            Next
            Return New String(chars)
        End Function

        Public Sub createpdf()
            Dim imagepath As String = Server.MapPath("Images")
            Dim code As String = codeGenerated(4)
            Dim doc As New Document
            Dim str As String = Server.MapPath("Sample.pdf")
            PdfWriter.GetInstance(doc, New FileStream(str, FileMode.Create))
            doc.Open()
            Dim gif As Image = Image.GetInstance(imagepath & "/logo_small.png")
            gif.Alignment = iTextSharp.text.Image.ALIGN_CENTER
            Dim Arial As Font = FontFactory.GetFont("Arial", 30)
            doc.Add(gif)
            doc.Add(New Paragraph("                        AR-" & code, Arial))
            doc.Add(New Paragraph("                               The draw is 13th june at Arwani both in Hall 8 at 3 pm"))
            doc.Close()
        End Sub
    End Class
End Namespace